package com.kgc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.kgc.config.AlipayConfig;
import com.kgc.pojo.Order;
import com.kgc.pojo.OrderEx;
import com.kgc.service.OrderService;
import com.kgc.service.TicketTypeService;
import com.kgc.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private TicketTypeService ticketTypeService;
    @RequestMapping("commitOrder")
    public Object addOrder(String out_trade_no, String total_price, String subject, String body) throws AlipayApiException {
        //jsp中的getparameter获取的参数当作方法形参，从前端发ajax过来接收，拼字符串操作后端来做
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_price +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //继续用map封装避免转json时出问题
        Map<String,Object> map = new HashMap<>();
        map.put("result",result);
        map.put("message","跳转支付宝页面");
        return map;

    }
    @RequestMapping("getOrderCount_yuan")
    public Object getOrderCount(Integer userId){
        System.out.println("userId"+userId);
        int count = orderService.getOrderCount(userId);
        return new Result(count,"获取商品数量成功");
    }
    /*订单管理信息*/
    @RequestMapping("getOrderInfo_yuan")
    public Object getOrderInfo(Integer pageNow, Integer pageSize, Integer userId){
        List<OrderEx> orderExList = orderService.getOrderInfo(pageNow,pageSize,userId);
        return new Result(orderExList,"获取订单列表成功！");
    }
    /*订单详情信息*/
    @RequestMapping("getOrderDetailInfo_yuan")
    public Object getOrderDetailInfo(Integer userId,Integer orderId){
        List<OrderEx> orderExDetailList = orderService.getOrderDetailInfo(userId,orderId);
        return new Result(orderExDetailList,"获取订单详情列表成功");
    }

    /*删除订单*/
    @RequestMapping("delOrderById_yuan")
    public Object delOrderById(Integer orderId){
        int count = orderService.delOrderById(orderId);
        if (count > 0){
            return new Result(count,"订单删除成功");
        }
        return new Result(count,"订单删除失败");
    }
    /*修改订单状态*/
    @RequestMapping("changeOrderStatus_yuan")
    public Object changeOrderStatus(Integer orderId){
        //System.out.println("controller层changeOrderStatus:id="+orderId);
        int count = orderService.changeOrderStatus(orderId);
        return new Result(count,"修改订单为已失效成功！");
    }

    /*获取订单剩余时间*/
    @RequestMapping("getRemainTime_yuan")
    public Object getRemainTime(Integer orderId){
        Date createdate = orderService.getOrderById(orderId).getCreatedate();
        long endTime = createdate.getTime() + 15 * 60 * 1000;
        long now = new Date().getTime();
        long remainTime = endTime - now;
        System.out.println("remainTime:"+remainTime);
        return new Result(remainTime,"获取剩余时间成功");
    }

    @Scheduled(cron = "0 0/5 * * * ?")//定时器，每5分钟执行一次
    public Object updateOrderState(){
        Integer orderStatusId = 1;
        List<OrderEx> orderList = orderService.getOrderList(orderStatusId);//取出所有未付款的订单
        for (int i=0;i<orderList.size();i++){
            Result remainTime = (Result) getRemainTime(orderList.get(i).getId());
            if ((Long)remainTime.getResult() <= 0){//订单已失效
                ticketTypeService.addTicketCount(orderList.get(i).getTickettypeid(),orderList.get(i).getOrdercounts());//将失效的订单数量返回库存
                changeOrderStatus(orderList.get(i).getId());//将订单改为失效状态
            }
        }
        return new Result("1","修改成功");
    }

}